<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/7/18
 * Time: 13:44
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\common\business;

use app\common\model\mysql\SpecsValue as ModelObj;
use app\common\validate\SpecsValue as ValidateObj;
use think\Exception;
use think\facade\Log;


class SpecsValue extends BusBase
{
    protected ?ModelObj $modelObj = null;
    protected ?ValidateObj $validateObj = null;
    //是否验证允许重复
    protected bool $repeat = true;
    //验证数据库重复字段
    protected string $repeat_string = 'title,specs_id';

    public function __construct()
    {
        $this->modelObj = new ModelObj();
        $this->validateObj = new ValidateObj();
    }

    /**
     * @param int $specs_id
     * @return array
     * @throws Exception
     */
    public function getBySpecsId(int $specs_id = 0): array
    {
        try {
            $result = $this->modelObj->getBySpecsId($specs_id, 'id,title as name');
        } catch (\Exception $e) {
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            throw new Exception("查询失败");
        }
        return $result;
    }

    /**
     * @param array $data
     * @return bool|int|string
     * @throws Exception
     */
    public function addById(array $data = [])
    {
        if (empty($data)) {
            throw new Exception("数据不完整");
        }
        $data['create_time'] = time();
        $data['update_time'] = time();
        //验证
        if (!$this->validateObj->scene('add')->check($data)) {
            throw new Exception($this->validateObj->getError());
        }
        //验证是否可以重复
        if ($this->repeat) {
            if (empty($this->repeat_string)) {
                throw new Exception("值不能为空");
            }
            $array = explode(',',$this->repeat_string);
            $map = [];
            foreach ($array as $k=>$v){
                $map[$k] = [
                    [$v,'=',$data[$v]]
                ];
            }
            //dump($map);exit();
            try {
                $res = $this->modelObj->getBaseRepeat($map);
            } catch (\Exception $e) {
                throw new Exception("操作失败");
            }
            if ($res) {
                throw new Exception("请不要重复添加");
            }
        }
        //dump($data);exit();
        //添加入库
        try {
            $res = $this->modelObj->addById($data);
        } catch (\Exception $e) {
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            throw new Exception("入库失败");
        }
        if ($res) {
            return $res;
        } else {
            return false;
        }
    }
}